package com.xbongbong.paas.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.LogicalSymbolEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.MathUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.RichTextEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/03/24 21:29
 */
public class FormDataUtil {


    public static void setSystemData(JSONObject data, PaasFormDataEntity paasFormDataEntity) {
        data.put(FieldTypeEnum.OWNERID.getAlias(), paasFormDataEntity.getOwnerId());
        data.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEntity.getSerialNo());
        data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEntity.getDepartmentId());
        data.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEntity.getUpdateTime());
        data.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEntity.getAddTime());
        data.put(FieldTypeEnum.CREATORID.getAlias(), paasFormDataEntity.getCreatorId());
    }

    public static void getDataSetSystemData(JSONObject data, PaasFormDataEntity paasFormDataEntity) {
        if (Objects.isNull(data) || Objects.isNull(paasFormDataEntity)) {
            return;
        }
       paasFormDataEntity.setOwnerId(data.getString(FieldTypeEnum.OWNERID.getAlias()));
       paasFormDataEntity.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
       paasFormDataEntity.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
       paasFormDataEntity.setCreatorId(data.getString(FieldTypeEnum.CREATORID.getAlias()));
       paasFormDataEntity.setAddTime(data.getLong(FieldTypeEnum.ADDTIME.getAlias()));
       paasFormDataEntity.setUpdateTime(data.getLong(FieldTypeEnum.UPDATETIME.getAlias()));
       paasFormDataEntity.setData(data);
    }

    /**
     * 移除系统字段
     * @param data
     */
    public static void removeSystemData(JSONObject data) {
        if (Objects.isNull(data)) {
            return;
        }
        // 兼容审批移除上一步data放入系统字段，如： ownerId, coUserId，请勿在此加非系统字段，如需加的话，请在各个业务层增加
        data.remove(FieldTypeEnum.COUSERID.getAlias());
        data.remove(FieldTypeEnum.OWNERID.getAlias());
        data.remove(FieldTypeEnum.SERIALNO.getAlias());
        data.remove(FieldTypeEnum.CREATORID.getAlias());
        data.remove(FieldTypeEnum.DEPARTMENTID.getAlias());
        data.remove(FieldTypeEnum.ADDTIME.getAlias());
        data.remove(FieldTypeEnum.UPDATETIME.getAlias());
        data.remove(FieldTypeEnum.DATAID.getAlias());
    }


    /**
     * 业务规则简易版-加减计算
     * @param targetField
     * @param targetData
     * @param targetAttr
     * @param value
     * @param symbol
     */
    public static BigDecimal count(FieldAttrEntity targetField, JSONObject targetData, String targetAttr, Object value, String symbol) throws XbbException {
        // 获取精度
        if (Objects.equals(LogicalSymbolEnum.EQUAL.getSymbol(), symbol)) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261012);
        }
        BigDecimal resultBig = null;
        Integer accuracy = Objects.equals(1, targetField.getIntegerOnly()) || targetField.getAccuracy() == null  ? 0 : targetField.getAccuracy();
        Double target = Objects.isNull(targetData) || targetData.getDouble(targetAttr) == null ? 0D : targetData.getDouble(targetAttr);
        Double thisValue =value == null || StringUtil.isEmpty(value.toString()) ? 0D : Double.valueOf(value.toString());
        // 计算顺序：【目标表单值】【累加/扣减】【当前表单值/固定值】
        if (Objects.equals(LogicalSymbolEnum.SUM.getSymbol(), symbol)) {
            Double result = Arith.add(target, thisValue);
            // 取整或者四舍五入
            resultBig = MathUtil.ceil(result, accuracy);
        } else if (Objects.equals(LogicalSymbolEnum.LESS.getSymbol(), symbol)) {
            Double result = Arith.sub(target, thisValue);
            // 取整或者四舍五入
            resultBig = MathUtil.ceil(result, accuracy);
        }
        return resultBig;
    }

    /**
     * 返回数据data中对应的键值格式
     *
     * @param dataKeys data数据中的key
     * @return
     */
    public static String getDataColumns(List<String> dataKeys) {
        if (CollectionsUtil.isEmpty(dataKeys)) {
            return null;
        }
        StringBuffer filterAttrBuffer = new StringBuffer();
        for (String attr : dataKeys) {
            filterAttrBuffer.append("'").append(attr).append("',").append("JSON_EXTRACT(data,'$.").append(attr).append("')");
        }
        return  "JSON_OBJECT("+ filterAttrBuffer.toString() +") AS data";
    }

    /**
     * 数据状态的通用校验：删除，审批中，回收站这种
     * @param paasFormDataEntityExt
     * @param subBusinessType
     * @throws XbbException
     */
    public static void checkData(PaasFormDataEntityExt paasFormDataEntityExt, Integer subBusinessType) throws XbbException {
        //审批中数据不让看，直接报错，目前这样处理，后续优化为可见，但没有任何操作权限
        if ( FlowStatusEnum.inApproval(paasFormDataEntityExt.getFlowStatus()) ) {
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200023);
        }

        if (Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.REMOVE_COMPLETELY.getDel())){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        boolean isDelete = !(Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.CLUE_RECYCLE.getCode())) && Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel());
        if (isDelete){
            // 客户回收站和线索回收站的单据del都是1
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
    }

    /**
     * Description: 获取照片url集合
     * 返回可能为null，获取之后需要进行非null判断
     * 重构前 -> com.xbongbong.saas.help.SaasUpdateHelp#getListFromFormData(com.alibaba.fastjson.JSONObject, java.lang.String)
     * @param data
     * @param attr
     * @return
     * @throws XbbException
     */
    public static List<Object> getListFromFormData(JSONObject data, String attr) throws XbbException {
        List<Object> photoList = new ArrayList<>();
        if (data == null || attr == null) {
            return photoList;
        }
        try {
            if (data.get(attr) == null) {
                return photoList;
            }
            JSONArray photoArray = data.getJSONArray(attr);
            for (Object obj : photoArray) {
                String tel = obj.toString();
                photoList.add(tel);
            }
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
        return photoList;
    }

    /**
     * json数据移除富文本
     *
     * @param data
     * @return
     */
    public static Object removeRichText(JSONObject data) {
        return data.remove(RichTextEnum.RICH_TEXT.getAttr());
    }
}
